package com.tianchi.lexiang.service;

import com.tianchi.lexiang.deep.SceneControl;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.IBinder;
import android.util.Log;

public class MediaPlayerService extends Service {
	
	private static final String TAG = "MediaPlayerService";
	
	public static final int START = 2000;
	public static final int STOP = 2001;
	
	public static final int UNKNOWN = -2000;
	public static final String COMMAND = "command";
	
	public static final String MEDIAPLAYER = "mpid";

	private int cmd;
	private int mpId;
	
	private MediaPlayer mp = null;
	
	
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		Log.d(TAG, "MediaPlayerService onCreate...");
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.d(TAG, "intent==>" + intent);
		if (intent == null) {
			Log.d(TAG, "intent is null ,return -1 in onStartCommand");
			return -1;
		}
		cmd = intent.getIntExtra(COMMAND, UNKNOWN);
		mpId = intent.getIntExtra(MEDIAPLAYER, 0);
		switch (cmd) {
		case START:
			handleStartCmd(mpId);
			break;
		case STOP:
			handleStopCmd();
			break;

		default:
			break;
		}
		
		return super.onStartCommand(intent, flags, startId);
	}
	
	private void handleStartCmd(int mpId) {
		try {
			Log.d(TAG, "[handleStartCmd].....mp==>" + mp);
			Log.d(TAG, "[handleStartCmd].....mpId==>" + mpId);
			if(mp != null){
				Log.d(TAG, "[handleStartCmd].....mp other stop");
				mp.stop();
				mp.release();
				mp = null;
			}
			mp = MediaPlayer.create(MediaPlayerService.this, mpId);
			mp.setOnCompletionListener(new OnCompletionListener() {
				
				@Override
				public void onCompletion(MediaPlayer media) {
					 Intent mIntent = new Intent(SceneControl.ACTION_NAME); 
		             sendBroadcast(mIntent); 
				}
			});
			mp.start();
		} catch (IllegalStateException e) {
			e.printStackTrace();
			Log.d(TAG, "[handleStartCmd].....e===>" + e.toString());
		}
	}

	private void handleStopCmd() {
		if(mp != null){
			try {
				mp.stop();
			} catch (IllegalStateException e) {
				e.printStackTrace();
				Log.d(TAG, "[handleStopCmd].....e===>" + e.toString());
			}
		}
	}

}
